package com.fr.chicken.pay.com.shb.pay.util;

import net.sf.json.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

public class HttpUtils {
    /**
     * 发送post请求--用于接口接收的参数为JSON字符串
     * @param url 请求地址
     * @param params json格式的字符串
     * @return
     */
    public static String httpPost(String url, String params){
        String result = null;
        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            /*
             * 发送json字符串，这两句需要设置
             */
            httpPost.addHeader("Content-type","application/json; charset=utf-8");
            httpPost.setHeader("Accept", "application/json");

            httpPost.setEntity(new StringEntity(params, "UTF-8"));

            enableSSL((DefaultHttpClient) httpClient);
            HttpResponse response = httpClient.execute(httpPost);

            int statusCode = response.getStatusLine().getStatusCode();

            if (statusCode == HttpStatus.SC_OK) {
                // Read the response body
                result = EntityUtils.toString(response.getEntity(),"UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 发送post请求--用于接口接收的参数为键值对
     * @param url 请求地址
     * @param nameValuePairs 键值对
     * @return
     */
    public static String httpPost(String url, List<NameValuePair> nameValuePairs) {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        String strResult = "";

        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
            HttpResponse response = httpClient.execute(httpPost);

            if (response.getStatusLine().getStatusCode() == 200) {
                /* 读返回数据 */
                strResult = EntityUtils.toString(response.getEntity());
                // System.out.println("conResult:"+conResult);
            } else {
                strResult += "发送失败:" + response.getStatusLine().getStatusCode();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return strResult;
    }

    public static String httpGet(String url, List<NameValuePair> nameValuePairs){
        HttpClient httpClient = new DefaultHttpClient();
        String sb = "";
        String result = "";
        try {
            for(NameValuePair nvp:nameValuePairs){
                sb += nvp.getName()+"="+nvp.getValue()+"&";
            }
            sb = sb.substring(0,sb.length()-1);
            sb = URLDecoder.decode(sb, "UTF-8");
            HttpGet httpGet = new HttpGet(url+"?"+sb);

            HttpResponse response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {
                /* 读返回数据 */
                result = EntityUtils.toString(response.getEntity());
            } else {
                result += "发送失败:" + response.getStatusLine().getStatusCode();
            }

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }


    /**
     * 访问https的网站
     *
     * @param httpclient
     */
    public static void enableSSL(DefaultHttpClient httpclient) {
        // 调用ssl
        try {
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(null, new TrustManager[]{truseAllManager}, null);
            SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
            sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            Scheme https = new Scheme("https", sf, 443);
            httpclient.getConnectionManager().getSchemeRegistry().register(https);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 重写验证方法，取消检测ssl
     */
    public static TrustManager truseAllManager = new X509TrustManager() {

        @Override
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType)
                throws java.security.cert.CertificateException {
        }

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType)
                throws java.security.cert.CertificateException {
        }

    };


    public static void main(String[] args) {
        String url = "http://10.140.8.56/gd_fssc/rest/fsscService/getStaffInfo";
        String url2 = "http://localhost:8080/eshore-app-backframe-web/interface/getJson";

        // 发送 POST 请求
        JSONObject json = new JSONObject();
        json.put("number", "44053211@GD");
        httpPost(url,json.toString());

        List<NameValuePair> nameValuePairs = new ArrayList<>();
        nameValuePairs.add(new BasicNameValuePair("method", "login"));
        httpGet(url2,nameValuePairs);
    }

}
